from http.server import BaseHTTPRequestHandler, HTTPServer
import sqlite3
import json, re
from website.site_list import site_list
from lib.m3u8 import M3U8
import importlib


class Sqlite(object):
    @classmethod
    def get_data(cls, db_path, table_name, page, page_size):
        # 连接SQLite数据库
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()

        # 计算起始行数和结束行数
        start_row = (page - 1) * page_size
        end_row = start_row + page_size

        # 查询指定范围的数据
        cursor.execute(f"SELECT * FROM {table_name} LIMIT {start_row}, {end_row}")
        data = cursor.fetchall()

        # 关闭数据库连接
        conn.close()

        # 将数据转换为JSON格式并返回
        return json.dumps(data, ensure_ascii=False)


class DbRes(object):

    @classmethod
    def get_db_path(cls, db_name):
        """
        通过db名称找到db路径
        """

        db_path = f"website/{db_name}/{db_name}.db"
        return db_path

    @classmethod
    def get_support_websites(cls):
        """
        加载所有支持的网站，以及网站分类
        """

        website_list = [{
            "db_name": "",
            "website_name": "",
            "website_url": "",
            "class": []
        }]

        return website_list

    @classmethod
    def get_class_list(cls, db, table_name="class"):
        conn = sqlite3.connect(db)
        cursor = conn.cursor()

        # 查询指定范围的数据
        cursor.execute(f"SELECT * FROM {table_name}")
        data = cursor.fetchall()

        # 关闭数据库连接
        conn.close()

        # 将数据转换为JSON格式并返回
        return data

    @classmethod
    def get_resource_list(cls, db, table_name="resource", class_id=None, page_num=1, page_size=10):
        conn = sqlite3.connect(db)
        cursor = conn.cursor()

        # 计算起始行数和结束行数
        start_row = (page_num - 1) * page_size
        end_row = start_row + page_size

        # 查询指定范围的数据
        if class_id:
            sql = f"SELECT * FROM {table_name} WHERE class_id={class_id} LIMIT {start_row}, {end_row}"
        else:
            sql = f"SELECT * FROM {table_name} LIMIT {start_row}, {end_row}"
        print(sql)
        cursor.execute(sql)
        data = cursor.fetchall()

        # 关闭数据库连接
        conn.close()

        # 将数据转换为JSON格式并返回
        return data


class WebHandle(object):
    site_cols = [["name", "名称"], ["url", "网址"], ["id", "ID"]]
    class_cols = [["name", "名称"], ["res_count", "资源总数"], ["id", "ID"]]
    res_cols = [["name", "名称"], ["head_image", "图片"], ["video", "视频播放"], ["id", "ID"], ["class_id", "CLASS ID"]]

    @classmethod
    def get_website_list(cls):
        """
        加载网站列表
        """

        data = {
            "cols": cls.site_cols,
            "rows": site_list,
            "name": "网站列表"
        }
        return data

    @classmethod
    def get_class_list(cls, website_id):
        """
        加载网站列表
        """

        db = DbRes.get_db_path(db_name=website_id)
        db_class_list = DbRes.get_class_list(db=db)
        """
            id TEXT PRIMARY KEY, 
            name TEXT NOT NULL, 
            res_type TEXT NOT NULL,
            url TEXT NOT NULL,
            page_count INTEGER,
            res_count INTEGER
        """

        class_list = list(map(lambda x: {"id": x[0], "name": x[1], "res_count": x[5]}, db_class_list))
        # print(class_list)

        data = {
            "cols": cls.class_cols,
            "rows": class_list,
            "name": "分类列表"
        }
        return data

    @classmethod
    def get_resource_list(cls, website_id, class_id, page_num=1, page_size=10):
        """
        加载网站列表
        """
        try:
            db = DbRes.get_db_path(db_name=website_id)
            db_res_list = DbRes.get_resource_list(db=db, class_id=class_id, page_num=page_num, page_size=page_size)
            """
            id TEXT NOT NULL, 
            class_id TEXT NOT NULL, 
            name TEXT NOT NULL,
            url TEXT,
            res_type TEXT,
            head_image TEXT,
            text TEXT,
            images TEXT,
            video TEXT,
            label1 TEXT,
            label2 TEXT,
            label3 TEXT,
            parse INTEGER,
            finish INTEGER,
            PRIMARY KEY (id, class_id)
            foreign key(class_id) references class (id)
            """

            res_list = list(map(lambda x: {"id": x[0], "name": x[2], "class_id": x[1], "head_image": x[5], "video": x[8]}, db_res_list))
            data = {
                "cols": cls.res_cols,
                "rows": res_list,
                "name": "资源列表"
            }
            return data
        except Exception as exc:
            # 处理其他异常情况
            print(f"解析class index page 异常: {exc}")

    @classmethod
    def get_search_name_list(cls, website_id, search_name):
        """
        加载网站列表
        """

        data = {
            "cols": cls.class_cols,
            "rows": site_list,
            "name": "网站列表"
        }
        return data

    @classmethod
    def download_video(cls, m3u8, filename):
        """
        加载网站列表
        """

        M3U8.download_video(m3u8_url=m3u8, save_dir="server_web/download", filename=filename)
        return {"result": "success"}


# 定义处理不同路径的请求的处理函数
class MyHandler(BaseHTTPRequestHandler):

    def set_header(self, content_type):
        self.send_response(200)
        if content_type == "css":
            self.send_header("Content-type", "text/css")
        if content_type == "text":
            self.send_header("Content-type", "text/html")
        elif content_type == "json":
            self.send_header("Content-type", "application/json")
        elif content_type == "img":
            self.send_header("Content-type", "image/jpeg")
        self.end_headers()

    def send_image(self, path):
        self.set_header("img")
        image_file = f"server_web/image{path}"
        # 将图片文件的内容写入响应体
        with open(image_file, 'rb') as f:
            self.wfile.write(f.read())

    def send_text(self, path, c_type="text"):
        self.set_header(c_type)
        text_file = f"server_web{path}"
        # 将图片文件的内容写入响应体
        with open(text_file, 'rb') as f:
            self.wfile.write(f.read())

    def do_GET(self):
        # 处理GET请求

        if "/static/" in self.path:
            if self.path.endswith('.css'):
                return self.send_text(self.path, c_type="css")
            else:
                return self.send_text(self.path)
        elif "/image/" in self.path:
            return self.send_image(self.path)
        else:
            items = self.path.split("?")
            paths = list(filter(lambda x: len(x) > 0, items[0].split("/")))
            if len(items) > 1:
                params = items[-1].split("&")
            else:
                params = []

            print(paths)
            print(params)

            website_id = paths[0] if len(paths) > 0 else ""
            class_id = paths[1] if len(paths) > 1 else ""

            self.set_header(content_type="text")
            with open("server_web/table_page.html", "r", encoding='utf-8') as f:
                response = f.read()
                if website_id:
                    response = re.sub(r'p_website_id="[^"]*"', f"p_website_id='{website_id}'", response)
                    if class_id:
                        response = re.sub(r'p_table_type="[^"]*"', f"p_table_type='resource'", response)
                        response = re.sub(r'p_class_id="[^"]*"', f"p_class_id='{class_id}'", response)
                    else:
                        print("xxxxx")
                        response = re.sub(r'p_table_type="[^"]*"', f"p_table_type='class'", response)
                else:
                    response = re.sub(r'p_table_type="[^"]*"', f"p_table_type='website'", response)

                self.wfile.write(response.encode())



    def do_POST(self):
        # 处理POST请求
        content_length = int(self.headers["Content-Length"])
        data = self.rfile.read(content_length).decode()
        print(data)
        params = json.loads(data)
        # 在这里可以对POST请求的数据进行处理
        if self.path == "/website-list":
            self.set_header(content_type="json")
            response = WebHandle.get_website_list()
            response_str = json.dumps(response, ensure_ascii=False)
            self.wfile.write(response_str.encode())
        elif self.path == "/class-list":
            self.set_header(content_type="json")
            website_id = params.get("website_id")
            if website_id is None:
                response_str = "{'errmsg': '未知网站'}"
            else:
                response = WebHandle.get_class_list(website_id=website_id)
                response_str = json.dumps(response, ensure_ascii=False)

            self.wfile.write(response_str.encode())
        elif self.path == "/resource-list":
            self.set_header(content_type="json")
            website_id = params.get("website_id")
            class_id = params.get("class_id")
            page_num = params.get("page_num")
            if page_num is None:
                page_num = 1
            page_size = params.get("page_size")
            if page_size is None:
                page_size = 2
            if website_id is None:
                response_str = "{'errmsg': '未知网站'}"
            else:
                response = WebHandle.get_resource_list(website_id=website_id, class_id=class_id, page_num=page_num, page_size=page_size)
                response_str = json.dumps(response, ensure_ascii=False)
            self.wfile.write(response_str.encode())
        elif self.path == "/search-name":
            self.set_header(content_type="json")
            website_id = params.get("website_id")
            search_name = params.get("search_name")
            response = WebHandle.get_search_name_list(website_id=website_id, search_name=search_name)
            response_str = json.dumps(response, ensure_ascii=False)
            self.wfile.write(response_str.encode())
        elif self.path == "/download":
            self.set_header(content_type="json")
            m3u8 = params.get("m3u8")
            filename = params.get("filename")
            response = WebHandle.download_video(m3u8=m3u8, filename=filename)
            response_str = json.dumps(response, ensure_ascii=False)
            self.wfile.write(response_str.encode())


        #
        # response = "<html><body><h1>Received POST request</h1></body></html>"
        # self.wfile.write(response.encode())

    # 创建HTTPServer对象，绑定地址和端口，并设置处理函数


server_address = ("", 12345)
httpd = HTTPServer(server_address, MyHandler)

# 启动HTTPServer，开始监听请求
print(f"Server started {server_address}")
httpd.serve_forever()
